import React, { useState } from "react";
import { getMd5 } from "../../unitls/GetMd5";
function ReactLogo() {
  const [md5, setMD5] = useState(null);
  const [timestamp, setTime] = useState(0);
  let file = "";
  let timer = null;

  const startCalculateMD5 = async () => {
    if (!file) return;
    let time = 0;
    if (timer) clearInterval(timer);
    timer = setInterval(() => {
      // 更新计算时间
      time += 1;
      setTime(time);
      console.log("计算MD5中，已用时：", time, "s");
    }, 1000);

    try {
      // let md5Value = await getMd5(file)
      // setMD5(md5Value);

      const worker = new Worker(
        new URL("../../../public/webWorker.js", import.meta.url), {
          type: 'module', // 确保 Worker 作为模块加载
        }
      );
      worker.postMessage(file);
      const result = await new Promise((resolve, reject) => {
        worker.onmessage = (event) => {
          if (event.data.error) {
            reject(event.data.error);
          } else {
            resolve(event.data);
          }
          worker.terminate();
        };
        worker.onerror = (error) => {
          reject(error);
          worker.terminate();
        };
      });

      console.log("计算 MD5 成功:", result);
      setMD5(result);
      if (timer) clearInterval(timer);
    } catch (error) {
      if (timer) clearInterval(timer);
      console.error("计算MD5时出错:", error);
    }
  };

  return (
    <>
      <input
        type="file"
        name="file"
        id=""
        onChange={(e) => {
          file = e.target.files[0];
        }}
      />
      <p>
        <button
          onClick={() => {
            startCalculateMD5();
          }}
        >
          计算MD5
        </button>
      </p>
      <p>
        <span>计算MD5中，已用时：{timestamp}s</span>
        <br />
        <span>MD5值：{md5}</span>
      </p>
    </>
  );
}

export default ReactLogo;
